package owg.util.opengl;

import java.util.Arrays;

import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;

import owg.util.Calc;
import owg.util.euclidian.V2D;
import owg.util.euclidian.V3D;
import owg.util.opengl.models.HPRF;


public class LineBuffer
{
	final int vSize = 7;  
	int numVerts = 0;
	float[] buffer = new float[vSize*64];
	HPRF model = null;
	boolean outdated = true;
	
	public void put(V2D pos, float[] color4f)
	{
		put(pos.asV3D(), color4f);
	}
	public void put(double x, double y, float[] color4f)
	{
		put(new V3D(x, y, 0), color4f);
	}
	public void put(V3D pos, float[] color4f)
	{
		if(numVerts*vSize >= buffer.length)
		{
			//Must increase size of buffer
			buffer = Arrays.copyOf(buffer, buffer.length*2);
			//Old model cannot be reused because it is smaller
			if(model != null)
				model.dispose(model.egl);
			model = null;
		}
		//Put pos and color into buffer
		pos.toFloat(buffer, numVerts*vSize);
		System.arraycopy(color4f, 0, buffer, numVerts*vSize+3, 4);
		numVerts++;
		outdated = true;
	}
	
	public<X extends GL> void render(EGL<X> egl)
	{
		if(model == null)
		{
			HPRF m = egl.genModel("Overlay line buffer", true, false, GL2.GL_LINES, 3, false, 4, 0, 0); 
			//Must generate model
			m.setPrepackedVData(buffer);
			//ibuffer is redundant...
			int[] iBuffer = Calc.getCountingArray(0, buffer.length/vSize);
			m.setPrepackedIData(iBuffer);
			//limit rendering to current number of verts
			m.setRenderLimit(numVerts);
			m.end(egl);
			model = m;
			outdated = false;
		}
		else if(outdated)
		{
			//System.out.println(numVerts);
			model.requestVUpdate();
			//limit rendering to current number of verts
			model.setRenderLimit(numVerts);
			outdated = false;
		}
		//Render
		model.render();
	}
	
	public void clear()
	{
		numVerts = 0;
		outdated = true;
	}
}
